import cv2
from flask import Flask, request, jsonify, Response, send_file
import os
import shutil
from flask_cors import CORS  # 导入CORS模块
import util.index
import util.baidusdk

app = Flask(__name__)
CORS(app, resources={r'/*': {'origins': '*'}})
# 文件存储的目录
UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
# 设置文件上传大小限制为 16 MB
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  # 16 MB

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

content_type = 'image/jpeg'


def allowed_file(filename):
    return '.' in filename and \
        filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


CORS(app, resources={r"/*": {"origins": "*"}})


@app.route('/upload', methods=["post"])
def getCarPlate():  # put application's code here
    # 获取请求参数
    if 'file' not in request.files:
        return jsonify({'error': '上传的非图片'})

    file = request.files['file']

    if file.filename == '':
        return jsonify({'error': '没选择图片'})

    if file and allowed_file(file.filename):
        filename = file.filename
        # 创建filename 文件夹
        message = "上传图片成功"
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        if not os.path.exists("out/%s" % filename.split(".")[0]):
            os.mkdir("out/%s" % filename.split(".")[0])
        image = cv2.imread("./uploads/%s" % filename)  # 读取原始图像

        try:
            util.index.getPlate(image, filename)
        except Exception as e:

            message = "图片识别失败"
            text = util.baidusdk.get_car_plate(filename)
            print(text)
            # 删除文件夹
            shutil.rmtree("out/%s" % filename.split(".")[0])
            print(e)
            return jsonify({'message': message, "result": text, "code": 500, 'filename': filename})

        return jsonify({'message': message, "code": 200, 'filename': filename})
    else:
        return jsonify({'error': '无效'})


@app.route('/one/', methods=["get"])
def getCarPlate1():
    # 获取请求参数
    query_params = request.args.get('id')
    # 读取文件中的图片并返回
    return send_file("./out/%s/1.jpg" % query_params, mimetype=content_type)


@app.route('/two/', methods=["get"])
def getCarPlate2():
    # 获取请求参数
    query_params = request.args.get('id')

    # 读取文件中的图片并返回
    return send_file("./out/%s/2.jpg" % query_params, mimetype=content_type)


@app.route('/three/', methods=["get"])
def getCarPlate3():
    # 获取请求参数
    query_params = request.args.get('id')

    # 读取文件中的图片并返回
    return send_file("./out/%s/3.jpg" % query_params, mimetype=content_type)


@app.route('/four/', methods=["get"])
def getCarPlate4():
    # 获取请求参数
    query_params = request.args.get('id')

    # 读取文件中的图片并返回
    return send_file("./out/%s/4.jpg" % query_params, mimetype=content_type)


@app.route('/five/', methods=["get"])
def getCarPlate5():
    # 获取请求参数
    query_params = request.args.get('id')

    # 读取文件中的图片并返回
    return send_file("./out/%s/5.jpg" % query_params, mimetype=content_type)


@app.route('/six/', methods=["get"])
def getCarPlate6():
    # 获取请求参数
    query_params = request.args.get('id')

    # 读取文件中的图片并返回
    return send_file("./out/%s/6.jpg" % query_params, mimetype=content_type)


@app.route('/seven/', methods=["get"])
def getCarPlate7():
    # 获取请求参数
    query_params = request.args.get('id')

    # 读取文件中的图片并返回
    return send_file("./out/%s/7.jpg" % query_params, mimetype=content_type)


@app.route('/eight/', methods=["get"])
def getCarPlate8():
    # 获取请求参数
    query_params = request.args.get('id')

    # 读取文件中的图片并返回
    return send_file("./out/%s/8.jpg" % query_params, mimetype=content_type)


@app.route('/nine/', methods=["get"])
def getCarPlate9():
    # 获取请求参数
    query_params = request.args.get('id')

    # 读取文件中的图片并返回
    return send_file("./out/%s/9.jpg" % query_params, mimetype=content_type)


@app.route('/ten/', methods=["get"])
def getCarPlate10():
    query_params = request.args.get('id')
    # 读取文件中的txt文件内容返回
    with open("./out/%s/10.txt" % query_params, "r", encoding='utf-8') as f:
        content = f.read()
        return jsonify({'message': content, "code": 200})


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
